package com.csjy.migration.hnnd.business;

import com.csjy.migration.hnnd.*;
import com.csjy.migration.hnnd.annotation.BusinessDataConverter;
import com.csjy.migration.hnnd.dict.Bank;
import com.csjy.migration.hnnd.dict.RepayType;

import javax.script.ScriptException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *流程放款信息表
 */
@BusinessDataConverter(
        auto = false,
        insertSql = "INSERT INTO ND_BPM_LOAN_INFORMATION_FORM\n" +
                "(ID, CREATE_NAME, CREATE_BY, CREATE_DATE, UPDATE_NAME, UPDATE_BY, UPDATE_DATE, SYS_ORG_CODE, SYS_COMPANY_CODE, BPM_STATUS, PRO_ID, GUARANTEE_CONTRACT_NUMBER, LOAN_CONTRACT_NUMBER, CONTRACT_START_TIME, CONTRACT_EXPIRATION_TIME, ACTUAL_LOAN_AMOUNT, REPAYMENT_INTEREST_RATE, LOAN_TIME, LOAN_EXPIRATION_TIME, LOAN_REVIEW_TIME, ACTUAL_LENDING_BANK, BANK_BRANCH_NAME, APPLICATION_AMOUNT, GUARANTEED_CONTRACT_ID, GUARANTEED_CONTRACT_AMOUNT, PROC_ID, IS_VALID, TASK_ID, TASK_DEF_KEY, SOURCE_ID, TRREMARK, LOANVOUCHER_ID, REAL_ANNUAL_INTEREST, REVIEW_MARK, LENDING_NOTICE_NUMBER, LOAN_NOTIFICATION_ID, LOAN_NOTIFICATION_CREATE_DATE, PAYACCOUNTNO, LENDING_NOTICE_NUMBER_INDEX, SIGNEDORNOT)\n" +
                "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
        updateSql = "UPDATE ND_BPM_LOAN_INFORMATION_FORM\n" +
                "SET CREATE_NAME=?, CREATE_BY=?, CREATE_DATE=?, UPDATE_NAME=?, UPDATE_BY=?, UPDATE_DATE=?, SYS_ORG_CODE=?, SYS_COMPANY_CODE=?, BPM_STATUS=?, PRO_ID=?, GUARANTEE_CONTRACT_NUMBER=?, LOAN_CONTRACT_NUMBER=?, CONTRACT_START_TIME=?, CONTRACT_EXPIRATION_TIME=?, ACTUAL_LOAN_AMOUNT=?, REPAYMENT_INTEREST_RATE=?, LOAN_TIME=?, LOAN_EXPIRATION_TIME=?, LOAN_REVIEW_TIME=?, ACTUAL_LENDING_BANK=?, BANK_BRANCH_NAME=?, APPLICATION_AMOUNT=?, GUARANTEED_CONTRACT_ID=?, GUARANTEED_CONTRACT_AMOUNT=?, PROC_ID=?, IS_VALID=?, TASK_ID=?, TASK_DEF_KEY=?, SOURCE_ID=?, TRREMARK=?, LOANVOUCHER_ID=?, REAL_ANNUAL_INTEREST=?, REVIEW_MARK=?, LENDING_NOTICE_NUMBER=?, LOAN_NOTIFICATION_ID=?, LOAN_NOTIFICATION_CREATE_DATE=?, PAYACCOUNTNO=?, LENDING_NOTICE_NUMBER_INDEX=?, SIGNEDORNOT=?\n" +
                "WHERE ID = ?",
        findMigratedIdListSql = "SELECT ID FROM ND_BPM_LOAN_INFORMATION_FORM WHERE PROC_ID = ?"
)
public class NdbBpmLoanInformationForm extends AbstractWorkflowBusiness {

  private String lastFirstTaskId = null;

  NdLoanInformationForm ndLoanInformationForm = null;

  public String getLastFirstTaskId() {
    return lastFirstTaskId;
  }

  public void setLastFirstTaskId(String lastFirstTaskId) {
    this.lastFirstTaskId = lastFirstTaskId;
  }

  public NdbBpmLoanInformationForm(DbUtil sourceDbUtil, DbUtil targetDbUtil, SourceBusinessData sourceData, ProgramArgument programArgument, String projectId, String procInstId) throws SQLException {
    super(sourceDbUtil, targetDbUtil, sourceData, programArgument, projectId, procInstId);
    ndLoanInformationForm = new NdLoanInformationForm(sourceDbUtil,targetDbUtil,sourceData,programArgument,projectId);
  }

  @Override
  public void migrate() throws Exception {
    List<Map> btItemAccountDetailList = this.sourceData.getBtItemAccountDetailList().stream()
            .filter(btItemAccountDetail->{
              String workflowNo = btItemAccountDetail.get("WORKFLOWNO") == null ? null : btItemAccountDetail.get("WORKFLOWNO").toString();
              return workflowNo.equals(this.procInstId) && btItemAccountDetail.get("ACCOUNTTYPE").toString().equals("1");
            })
            .collect(Collectors.toList());

    for(Map.Entry<String,Map<String,Object>> entry : taskParamMap.entrySet()) {

      String curJbpmTaskInstanceId = entry.getKey();
      Map<String,Object> taskParam = entry.getValue();

      boolean duplicateFlag = false;

      if(btItemAccountDetailList.size() == 0 && this.programArgument.getAutoGenLoanInfo().equals("1")) {
        Map<String,Object> customBtItemAccountDetail = (Map<String,Object>)taskParam.get("customNdLoanInformation");
        if(!customBtItemAccountDetail.get("sencorType").equals("核保")) {
          btItemAccountDetailList.add(customBtItemAccountDetail);
          duplicateFlag = true;
        }
      }

      for (Map row : btItemAccountDetailList) {
        try {
          // 判断是否需要覆盖迁移
          String id = row.get("ACCOUNTNO").toString()+"-"+curJbpmTaskInstanceId;
          if(duplicateFlag) {
            id = row.get("ACCOUNTNO").toString();
          }
          int needMigratedResult = this.needMigrated(id);
          if(needMigratedResult == 0) {
            continue;
          }

          // 单条插入或更新
          if(needMigratedResult == 1) {
            this.targetDbUtil.updateByParams(updateSql,this.buildValues(row, curJbpmTaskInstanceId, taskParam,duplicateFlag),true);
          } else {
            this.targetDbUtil.updateByParams(insertSql,this.buildValues(row, curJbpmTaskInstanceId, taskParam,duplicateFlag));
          }

          if(duplicateFlag && lastFirstTaskId.equals(curJbpmTaskInstanceId)) {
            ndLoanInformationForm.customMigrate(row);
          }
        } catch(Exception e) {
          throw new Exception(String.format("流程实例[%s]-任务实例[%s]-放款数据（NdBpmLoanInformation)迁移失败:%s\n",this.procInstId, curJbpmTaskInstanceId, e.getMessage()));
        }
      }

      if(duplicateFlag) {
        btItemAccountDetailList.clear();
      }

    }
  }

  public List buildValues(Map row, String curJbpmTaskInstanceId, Map<String,Object> taskParam, boolean duplicateFlag) throws ScriptException, SQLException {
    List values = new ArrayList();
    String id = row.get("ACCOUNTNO").toString()+"-"+curJbpmTaskInstanceId;
    if(duplicateFlag) {
      id = row.get("ACCOUNTNO").toString();
    }
    //ID	主键
    values.add(id);
    //CREATE_NAME	创建人名称
    values.add(null);
    //CREATE_BY	创建人登录名称
    values.add(null);
    //CREATE_DATE	创建日期
    values.add(row.get("CREATE_TIME"));
    //UPDATE_NAME	更新人名称
    values.add(null);
    //UPDATE_BY	更新人登录名称
    values.add(null);
    //UPDATE_DATE	更新日期
    values.add(row.get("MODIFY_TIME"));
    //SYS_ORG_CODE	所属部门
    values.add(null);
    //SYS_COMPANY_CODE	所属公司
    values.add("002");
    //BPM_STATUS	流程状态
    values.add(1);
    //PRO_ID	项目ID
    values.add(this.projectId);
    //GUARANTEE_CONTRACT_NUMBER	保证合同编号
    values.add(row.get("PROMCONTRACTNO"));
    //LOAN_CONTRACT_NUMBER	借款合同编号
    values.add(row.get("LOANCONTRACTNO"));
    //CONTRACT_START_TIME	保证合同开始时间
    values.add(null);
    //CONTRACT_EXPIRATION_TIME	保证合同到期时间
    values.add(null);
    //ACTUAL_LOAN_AMOUNT	实际放款金额
    values.add(row.get("OCCURSUM"));
    //REPAYMENT_INTEREST_RATE	还款年息利率
    values.add(row.get("YEARRATE"));
    //LOAN_TIME	放款发生时间
    values.add(row.get("OCCURTIME"));
    //LOAN_EXPIRATION_TIME	放款到期时间
    values.add(row.get("ENDTIME"));
    //LOAN_REVIEW_TIME	放款复核时间
    values.add(null);
    //ACTUAL_LENDING_BANK	实际放款银行
    values.add(DictTool.getTargetDictCode(Bank.class,row.get("BANKID")));
    //BANK_BRANCH_NAME	银行支行名称
    values.add(row.get("BANKBRANCH"));
    //APPLICATION_AMOUNT	本次申请放款金额
    values.add(row.get("OCCURSUM"));
    //GUARANTEED_CONTRACT_ID	保证合同信息ID
    if(row.get("PROMCONTRACTNO") == null) {
      values.add(null);
    } else {
      values.add(MD5Utils.stringToMD5(row.get("PROMCONTRACTNO").toString()+"-"+this.projectId+"-1"));
    }
    //GUARANTEED_CONTRACT_AMOUNT	签订保证合同金额
    values.add(taskParam.get("guaranteedContractAmount"));
    //PROC_ID	流程ID
    values.add(this.procInstId + "-JW");
    //IS_VALID	是否使用
    values.add("Y");
    //TASK_ID	任务ID
    values.add(curJbpmTaskInstanceId + "-JW");
    //TASK_DEF_KEY	节点ID
    values.add(taskParam.get("taskDefKey"));
    //SOURCE_ID	业务ID
    values.add(row.get("ACCOUNTNO"));
    //TRREMARK	说明
    values.add(Tool.decodeUnicode(row.get("ACCOUNTMEMO")));
    //LOANVOUCHER_ID	放款凭证id
    values.add(row.get("ELEFILESTORENAME") == null ? null : row.get("ELEFILESTORENAME").toString().replace("-",""));
    //REAL_ANNUAL_INTEREST	实际年利息率
    values.add(row.get("YEARRATE"));
    //REVIEW_MARK	复核标记
    values.add(null);
    //LENDING_NOTICE_NUMBER	放款通知书编号
    values.add(null);
    //LOAN_NOTIFICATION_ID	放款通知书ID
    values.add(null);
    //LOAN_NOTIFICATION_CREATE_DATE	放款通知书创建时间
    values.add(null);
    //PAYACCOUNTNO	银行卡号
    values.add(row.get("CLIENTBANKACCOUNT"));
    //LENDING_NOTICE_NUMBER_INDEX	放款通知书编号下标
    values.add(null);
    //SIGNEDORNOT	是否签章
    values.add(null);

    return values;
  }

}


